

/**
 * 后处理扩散圆  半径不能过大  不然会闪烁
 */

import RaderScanShader from '../shader/RaderScanShader.glsl?raw'
import { v4 as uuid } from 'uuid'

export default class RaderScan {
  /**
   * 
   * @param {*} viewer 
   * @param {*} positions 
   * @param {*} radius 
   * @param {*} options 
   */

  constructor(viewer, positions, radius, options = {}) {
    this._viewer = viewer
    this._delegate = undefined
    this._position = positions
    this._radius = radius || 10.0
    this._speed = options.speed || 1.0
    this._color = options.color || Cesium.Color.DEEPSKYBLUE
  }


  mounted() {

    let center = this._position
    let up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
      center,
      new Cesium.Cartesian3()
    )
    let self = this
    let time = new Date().getTime()
    this._delegate = new Cesium.PostProcessStage({
      name: uuid(),
      fragmentShader: RaderScanShader,
      uniforms: {
        centerWC: function () {
          return center
        },
        planeNormalWC: function () {
          return up
        },
        lineNormalWC: function () {
          let rotateQ = new Cesium.Quaternion()
          let rotateM = new Cesium.Matrix3()
          let east = Cesium.Cartesian3.cross(
            Cesium.Cartesian3.UNIT_Z,
            up,
            new Cesium.Cartesian3()
          )
          let now = new Date().getTime()
          let angle = Cesium.Math.PI * 2 * ((now - time) / 1e4) * self._speed
          Cesium.Quaternion.fromAxisAngle(up, angle, rotateQ)
          Cesium.Matrix3.fromQuaternion(rotateQ, rotateM)
          Cesium.Matrix3.multiplyByVector(rotateM, east, east)
          Cesium.Cartesian3.normalize(east, east)
          return east
        },
        radius: function () {
          return self._radius
        },
        color: function () {
          return self._color
        }
      }
    })
  }

  /**
   * 添加后处理效果
   * @returns 
   */

  start() {
    !this._delegate && this.mounted()

    this._delegate && this._viewer.scene.postProcessStages.add(this._delegate)
    return this
  }

  /**
   * 停止渲染
   */

  stop() {
    this._delegate && this._viewer.scene.postProcessStages.remove(this._delegate)
    this._delegate = undefined
  }

}
